package com.toutou.base.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.ViewGroup.LayoutParams
import androidx.appcompat.app.AlertDialog
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ScreenUtils
import com.toutou.base.R
import com.toutou.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.getVmClazz
import me.hgj.jetpackmvvm.ext.inflateBindingWithGeneric


abstract class BaseDialog<VM: BaseViewModel, DB:ViewDataBinding>(): DialogFragment() {
    lateinit var mViewModel: VM
    lateinit var mDatabind: DB

    override fun getViewLifecycleOwner(): LifecycleOwner {
        return this
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        mDatabind = inflateBindingWithGeneric(layoutInflater, null, false)
        mViewModel = ViewModelProvider(this)[getVmClazz(this)]
        initView()
        val dialog = context?.let {
            AlertDialog.Builder(it)
                .setView(mDatabind.root)
                .create()
        }?.apply {
            setCanceledOnTouchOutside(true)
            setCancelable(true)
            window?.apply {
                decorView.setHasTransientState(true)//保留视图状态，让高度限制生效
                setWindowAnimations(R.style.ActionSheetDialogAnimation)
                setGravity(android.view.Gravity.BOTTOM)
                setBackgroundDrawableResource(android.R.color.transparent)

                setLayout(LayoutParams.MATCH_PARENT, (ScreenUtils.getScreenHeight() * 0.85).toInt())
                decorView.setHasTransientState(false)//继续视图排列
            }
        }
        return dialog ?: super.onCreateDialog(savedInstanceState)
    }

    abstract fun initView()
}